// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })
  const db = cloud.database()
  const wxContext = cloud.getWXContext()

  app.router("getPublisher", async (ctx, next) => {
    const res = await db.collection('users')
      .where({
        _openid: event._openid
      }).get()
    if (res) {
      let data = {
        _openid: res.data[0]._openid,
        avatarUrl: res.data[0].avatarUrl,
        nickName: res.data[0].nickName,
      }
      ctx.body = {
        code: 200,
        data
      }
    }
  })

  app.router("confirmFinish", async (ctx, next) => {
    const res = await db.collection('list')
      .where({
        _id: event.id
      }).update({
        data: {
          status: 'finish',
          other: wxContext.OPENID
        }
      })
    if (res) {
      ctx.body = {
        code: 200,
        result: res.stats.updated
      }
    }


  })

  app.router("cancelFinish", async (ctx, next) => {
    const result = await db.collection('list').where({_id: event.id}).get()
    if(result.data[0].other === wxContext.OPENID || result.data[0]._openid === wxContext.OPENID)
    {
      const res = await db.collection('list')
      .where({
        _id: event.id
      })
      .update({
        data: {
          status: 'progress',
          other: null
        }
      })
      if (res) {
        ctx.body = {
          code: 200,
          result: res.stats.updated
        }
      }
    } else {
      ctx.body = {
        code: 403
      }
    }

  })

  return app.serve()
}